package com.ziyueyuwen.xiniao.controller.lesson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.HttpResUtil;
import com.ziyueyuwen.xiniao.base.HttpResContent;
import com.ziyueyuwen.xiniao.base.exception.base.NotNullException;
import com.ziyueyuwen.xiniao.base.exception.nullpoint.LessonNotExistException;
import com.ziyueyuwen.xiniao.bean.ao.LessonSaveAO;
import com.ziyueyuwen.xiniao.bean.ao.LessonUpdateVO;
import com.ziyueyuwen.xiniao.bean.ao.TransferStudentAO;
import com.ziyueyuwen.xiniao.bean.ZyClassLessonInfo;
import com.ziyueyuwen.xiniao.bean.homework.ItemData;
import com.ziyueyuwen.xiniao.bean.homework.QuestionInfo;
import com.ziyueyuwen.xiniao.bean.homework.ZyHomeworkRecordDO;
import com.ziyueyuwen.xiniao.bean.homework.ZySubjectQuestionDO;
import com.ziyueyuwen.xiniao.bean.page.PageData;
import com.ziyueyuwen.xiniao.bean.query.LessonQuery;
import com.ziyueyuwen.xiniao.bean.report.ReportUpdateVO;
import com.ziyueyuwen.xiniao.bean.report.StudentLessonReportVO;
import com.ziyueyuwen.xiniao.bean.report.ZyStudentLessonReport;
import com.ziyueyuwen.xiniao.bean.select.SelectBean;
import com.ziyueyuwen.xiniao.bean.vo.*;
import com.ziyueyuwen.xiniao.enums.HomeworkStatusEnum;
import com.ziyueyuwen.xiniao.enums.ParamTypeEnum;
import com.ziyueyuwen.xiniao.service.*;
import com.ziyueyuwen.xiniao.service.baseservice.lesson.ZyClassLessonService;
import com.ziyueyuwen.xiniao.service.report.ReportService;
import com.ziyueyuwen.xiniao.util.DateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;

import static com.ziyueyuwen.xiniao.base.BaseUtil.checkParam;
import static com.ziyueyuwen.xiniao.base.BaseUtil.saveErrorMsgAndData;
import static com.ziyueyuwen.xiniao.base.BaseUtil.saveSuccessMsgAndData;
import static com.ziyueyuwen.xiniao.util.DateUtil.DEFAULT_FORMAT_PATTERN_1;
import static com.ziyueyuwen.xiniao.util.DateUtil.DEFAULT_FORMAT_PATTERN_3;

/**
 * @author wancheng  on 2018/12/24.
 */
@Validated
@Controller
@RequestMapping("/lesson")
public class LessonController {

    private final Logger logger = LoggerFactory.getLogger(LessonController.class);

    private final Integer LESSON_BEFORE_START_CHECK = 20;
    @Autowired
    LessonService lessonService;
    @Autowired
    UserService userService;
    @Autowired
    ZyClassLessonService zyClassLessonService;
    @Autowired
    MessageTaskTemplateService messageTaskTemplateService;
    @Autowired
    ReportService reportService;
    @Autowired
    SubjectQuestionService subjectQuestionService;
    @Autowired
    HomeworkRecordService homeworkRecordService;

    @RequestMapping(value = "/get_student_and_lesson.do", method = RequestMethod.POST)
    public void saveClass(HttpServletRequest request,
                          HttpServletResponse response,
                          Integer lessonId) {
        HttpResContent<Map<String, Object>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取学生信息和课节信息");
        try {
            String studentAccount = hrc.getUserInfo().getUserAccount();
            ZyUserVO student = userService.getUserMessage(studentAccount);
            ZyLessonVO lesson = lessonService.getClassAndCourseByLessonId(lessonId);
            Map<String, Object> res = new HashMap<>(8);
            res.put("studentName", student.getUserName());
            res.put("courseName", lesson.getCourse().getCourseName());
            res.put("lessonIndex", lesson.getLessonIndex());
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_lesson_student_message_by_lesson_id.do", method = RequestMethod.POST)
    public void getLessonUserMessage(HttpServletRequest request,
                                     HttpServletResponse response,
                                     Integer lessonId) {
        HttpResContent<List<LessonUserMessageVO>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取课节学生详情");
        try {
            if (lessonId == null) {
                throw new NotNullException("lessonId");
            }
            List<LessonUserMessageVO> res = lessonService.lessonUserMessage(lessonId);
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }



    @RequestMapping(value = "/lesson_save_batch.do", method = RequestMethod.POST)
    public void lessonSave(HttpServletRequest request,
                           HttpServletResponse response,
                           @Validated LessonSaveAO lesson) {
        HttpResContent<List<ZyClassLessonInfo>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("排课添加");
        try {
            logger.info("批量添加排课参数:lesson={}", JSON.toJSONString(lesson));
            String userAccount = hrc.getUserInfo().getUserAccount();
            List<ZyClassLessonInfo> error = lessonService.saveLesson(lesson, userAccount);
            saveSuccessMsgAndData(hrc, error);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/lesson_delete.do", method = RequestMethod.POST)
    public void lessonDelete(HttpServletRequest request,
                             HttpServletResponse response,
                             Integer lessonId) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("课节删除");
        try {
            if (lessonId == null) {
                throw new Exception("课节id为空");
            }
            ZyClassLessonInfo lessonInfo = zyClassLessonService.getByPreKey(lessonId);
            if (lessonInfo == null) {
                throw new LessonNotExistException();
            }
            if (new Date().after(DateUtil.addMinute(lessonInfo.getBeginTime(), LESSON_BEFORE_START_CHECK))) {
                throw new Exception("已上的课节无法删除");
            }
            String userAccount = hrc.getUserInfo().getUserAccount();
            lessonService.deleteLesson(lessonId, userAccount);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }


    @RequestMapping(value = "/lesson_update.do", method = RequestMethod.POST)
    public void lessonUpdate(HttpServletRequest request,
                             HttpServletResponse response,
                             @Validated LessonUpdateVO updateLesson) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("课节修改");
        try {
            //判断课节是否可以编辑逻辑
            if (updateLesson.getLessonId() == null) {
                throw new Exception("课节id为空");
            }
            ZyClassLessonInfo exist = zyClassLessonService.getByPreKey(updateLesson.getLessonId());
            if (exist == null) {
                throw new LessonNotExistException();
            }
            Date currentDate = new Date();
            if (exist.getEndTime().before(currentDate)) {
                throw new Exception("已上完的课节无法编辑");
            }
            Date updateBegin = DateUtil.str2Date(updateLesson.getDay() + " " + updateLesson.getStartTime(), DEFAULT_FORMAT_PATTERN_3);
            Date updateEnd = DateUtil.addHour(updateBegin, updateLesson.getDurationOfHour());
            updateEnd = DateUtil.addMinute(updateEnd, updateLesson.getDurationOfMinute());
            if (currentDate.after(exist.getBeginTime()) || DateUtil.date2Str(currentDate, DEFAULT_FORMAT_PATTERN_1)
                    .equals(DateUtil.date2Str(exist.getBeginTime(), DEFAULT_FORMAT_PATTERN_1))) {
                if (!updateBegin.equals(exist.getBeginTime()) || !updateEnd.equals(exist.getEndTime())) {
                    throw new Exception("正在上的课节或当天的课节无法编辑时间");
                }
            }
            String userAccount = hrc.getUserInfo().getUserAccount();
            //修改课节业务逻辑
            lessonService.updateLesson(updateLesson, userAccount);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_lesson_by_id.do", method = RequestMethod.POST)
    public void getLessonById(HttpServletRequest request,
                              HttpServletResponse response,
                              Integer lessonId) {
        HttpResContent<LessonInfoPageVO> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("通过id获取课节");
        try {
            if (lessonId == null) {
                throw new Exception("课节id为空");
            }
            LessonInfoPageVO res = lessonService.getByLessonId(lessonId);
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_lesson_for_page.do", method = RequestMethod.POST)
    public void getLessonForPage(HttpServletRequest request,
                                 HttpServletResponse response,
                                 @Validated LessonQuery query) {
        HttpResContent<PageData> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("排课分页");
        try {
            PageData res = lessonService.getLessonForPage(query);
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }


    @RequestMapping(value = "/add_transfer_student.do", method = RequestMethod.POST)
    public void addTransferStudent(HttpServletRequest request,
                                   HttpServletResponse response,
                                   @Validated TransferStudentAO transferStudent) {
        HttpResContent<JSONObject> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("插班生修改");
        try {
            JSONObject res = lessonService.updateTransferStudent(transferStudent);
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_teacher.do", method = RequestMethod.POST)
    public void getTeacher(HttpServletRequest request,
                           HttpServletResponse response,
                           Integer classId) {
        HttpResContent<List<List<SelectBean>>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取当前班级的老师");
        try {
            if (classId == null) {
                throw new Exception("班级id为空");
            }
            List<ZyClassUserVO> data = lessonService.getClassTeacher(classId);
            Map<Boolean, List<ZyClassUserVO>> booleanMap = data.stream().collect(Collectors.groupingBy(ZyClassUserVO::getIfCurrentClassTeacher));
            List<List<SelectBean>> res = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(booleanMap.get(true))) {
                List<SelectBean> selectBeans = booleanMap.get(true).stream().map(u -> new SelectBean(u.getUserName(), u.getUserAccount())).collect(Collectors.toList());
                res.add(selectBeans);
            }
            if (CollectionUtils.isNotEmpty(booleanMap.get(false))) {
                List<SelectBean> selectBeans = booleanMap.get(false).stream().map(u -> new SelectBean(u.getUserName(), u.getUserAccount())).collect(Collectors.toList());
                res.add(selectBeans);
            }
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

}
